import React, { Component, SFC } from 'react';
import {
    BrowserRouter as Router,
    Redirect,
    Route,
    Switch,
    RouteProps,
    useLocation,
    useHistory
} from 'react-router-dom';

import Home from './Home';
import { ROUTE_URL_MAP } from '../constants/route-url';
import Login from './Login';
import commonInteractor from '../core/interactor/common';

const ScreenRouter = () => {
    return (
        <Router>
            <Switch>
                <Route exact path="/" render={() => <Redirect to={ROUTE_URL_MAP.home} />} />
                <Route path={ROUTE_URL_MAP.login}>
                    <Login />
                </Route>
                <PrivateRoute path={ROUTE_URL_MAP.home}>
                    <Home />
                </PrivateRoute>
                <Route path="/403">
                    <NoMatch tip="No primer for" />
                </Route>
                <Route path="*">
                    <NoMatch tip="No match for" />
                </Route>
            </Switch>
        </Router>
    );
};

const NoMatch: SFC<{ tip: string }> = ({ tip }) => {
    const location = useLocation();
    const history = useHistory();
    const goToHome = () => history.push(ROUTE_URL_MAP.home);
    return (
        <div>
            <h3>
                {tip} <code>{location.pathname}</code>
            </h3>
            <button onClick={goToHome}>go to home</button>
        </div>
    );
};

const PrivateRoute: SFC<RouteProps> = ({ children, ...rest }) => {
    return (
        <Route
            {...rest}
            render={({ location }) => {
                if (commonInteractor.getAuthToken()) {
                    return children;
                } else {
                    return (
                        <Redirect
                            to={{ pathname: ROUTE_URL_MAP.login, state: { form: location } }}
                        />
                    );
                }
            }}
        />
    );
};

export default ScreenRouter;
